import React from 'react';
import config from "../config/config";
import { message, Modal } from 'antd';
import * as loginService from '../services/loginService';
import {getRoleByUser} from "../services/loginService";

export default {
  namespace: "loginModel",
  state: {
    homeView: null,
    tokenModel: null,
    codeModel: null,
    pageLoading: false,
    timeoutModalCount: 0,
    systemStatus: "login",
  },
  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload }
    }
  },
  effects: {
    *getAuthCode({ payload: params }, { select, call, put }) {
      const res = yield call(loginService.getAuthCode, params);
      if (res.code == "200") {
        console.log("loginModel Authentication Code ===> " + JSON.stringify(res.data));
        yield put({ type: "updateState", payload: { codeModel: res.data, systemStatus: "login" }});
      }
    },

    *login({ payload: params }, { select, call, put }) {
      console.log("===== loginModel login =====");
      yield put({ type: "updateState", payload: { pageLoading: true }});
      const { userName, password } = params;
      const { codeModel } = yield select(state => state.loginModel);
      const res = yield call(loginService.login, { userName, password, code: codeModel.code });
      console.log("===== loginModel login res ===== " + res);
      if (res.code == "200") {
        console.log(res);
        window._USERINFO_ = res.data;
        window._TOKEN_ = res.data.token;
        sessionStorage.token = window._TOKEN_;
        sessionStorage.userInfo = JSON.stringify(window._USERINFO_);

        const roleRes = yield call(loginService.getRoleByUser, { userId: res.data.userId });
        console.log("===== loginModel login roleRes ===== " + roleRes);
        if (roleRes.code == "200") {
          let roleList = roleRes.data.filter(item => item.name == "超级管理员");
          if (roleList.length > 0) {
            sessionStorage.systemStatus = "kunlun";
            yield put({ type: "updateState", payload: { tokenModel: res.data, systemStatus: "kunlun" }});
            window.location.href = "http://localhost:8000/kunlun";
          } else {
            sessionStorage.systemStatus = "app";
            yield put({ type: "updateState", payload: { tokenModel: res.data, systemStatus: "app" }});
            window.location.href = "http://localhost:8000/app";
          }
        }
      } else {
        message.error(res.message);
        console.log(res.error);
      }
      yield put({ type: "updateState", payload: { pageLoading: false }});
    },

    *logout({ payload: params }, { select, call, put }) {
      yield put({ type: "updateState", payload: { pageLoading: true }});
      const { userName, password } = window._USERINFO_ ? JSON.parse(window._USERINFO_) : JSON.parse(sessionStorage.userInfo);
      const res = yield call(loginService.logout, { userName, password });
      if (res.code == "200") {
        console.log("loginModel logout res => ", res);
      }
      yield put({ type: "updateState", payload: { pageLoading: false, paneTabs: [], activeHeadMenuKey: "home", activeSideMenuKey: null, systemStatus: "logout" }});
    },

    *handleTimeout({payload: params}, {select, call, put}) {
      const {dispatch} = params;
      let {timeoutModalCount} = yield select(state => state.loginModel);
      if (timeoutModalCount > 0) return;
      timeoutModalCount++;

      Modal.confirm({
        title: '提示',
        okText: "确认",
        cancelText: "取消",
        content: "离开时间太长，请重新登录！",
        onOk() {
          dispatch({type: "logout", payload: {}}).then(() =>
            window.location.href = "http://localhost:8000"
          );
        },
        onCancel() {
          timeoutModalCount--;
          dispatch({type: "updateState", payload: {timeoutModalCount}});
        },
      });
      dispatch({type: "updateState", payload: {timeoutModalCount}});
    },
  },
  subscriptions: {
    onListenIFrameMessage({ dispatch, history }) {
      window.addEventListener("message", function (e) {
        // 监听页面超时事件，确定后直接跳转到登陆界面
        console.log("loginModel Listener e => ", e);
        if (e.data && e.data.operateType == "timeout") {
          dispatch({type: "handleTimeout", payload: { dispatch }});
        }
      });
    },
    setup({ dispatch, history }) {
      const pathname = window.location.pathname;
      console.log("loginModel subscriptions setup pathname => ", pathname);
      if (pathname == "/") {
        dispatch({type: "getAuthCode", payload: {}});
      }
    },
  },
};
